<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Server-sent events demo</title>
</head>

<body>
    <button>Close the connection</button>

    <ul>
    </ul>

    <script>
        var param = 'access_token=' + getQueryString('access_token');
        var button = document.querySelector('button');
        var evtSource = new EventSource('sse.php?' + param, {
            'withCredentials': false
        });
        console.log('withCredentials:' + evtSource.withCredentials);
        console.log(evtSource.readyState);
        console.log(evtSource.url);
        var eventList = document.querySelector('ul');

        evtSource.onopen = function () {
            console.log("Connection to server opened.");
        };

        evtSource.onmessage = function (e) {
            var newElement = document.createElement("li");

            newElement.textContent = "message: " + e.data;
            eventList.appendChild(newElement);
        };

        evtSource.onerror = function () {
            console.log("EventSource failed.");
        };

        button.onclick = function () {
            console.log('Connection closed');
            evtSource.close();
        };

        evtSource.addEventListener("ping", function (e) {
            var newElement = document.createElement("li");

            var obj = JSON.parse(e.data);
            newElement.innerHTML = "ping at " + obj.time;
            eventList.appendChild(newElement);
        }, false);


        function getQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
    </script>
</body>

</html>